package com.flx.noodle.websocket.controller;

import com.flx.noodle.websocket.entity.ChatRoom;
import com.flx.noodle.websocket.entity.SSOUser;
import com.flx.noodle.websocket.searcher.RoomSearcher;
import com.flx.noodle.websocket.service.RoomService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import util.WsConstant;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * Created by fenglixiong on 2017/10/2.
 */
@Controller
@RequestMapping("/room")
public class RoomController {

    @Autowired
    private RoomService roomService;

    @RequestMapping("/roomList.htm")
    public String roomList(@RequestParam(value = "page",required = false,defaultValue = "1")Integer page,
                           @RequestParam(value = "pageSize",required = false,defaultValue = "10")Integer pageSize,
                           @RequestParam(value = "chatId",required = false)Integer chatId,
                           @RequestParam(value = "userId",required = false)Integer userId,
                           HttpServletRequest request, ModelMap model){
        RoomSearcher searcher = new RoomSearcher();
        searcher.setPage(page);
        searcher.setPageSize(pageSize);
        searcher.setChatId(chatId);
        searcher.setUserId(userId);
        List<ChatRoom> roomList = roomService.findRoomList(searcher);
        model.addAttribute("ps",searcher);
        model.addAttribute("roomList",roomList);
        return "room/room_list";
    }

    @RequestMapping("/roomAdd.htm")
    public String addRoom(){
        return "room/room_add";
    }

    @RequestMapping("/roomEdit.htm")
    public String editRoom(@RequestParam(value = "roomId")Integer roomId,ModelMap model){
        ChatRoom chatRoom = roomService.getRoomById(roomId);
        model.addAttribute("room",chatRoom);
        return "room/room_add";
    }

    @RequestMapping("/saveOrUpdate.htm")
    public String saveOrUpdate(@ModelAttribute ChatRoom chatRoom,HttpServletRequest request){
        SSOUser ssoUser = (SSOUser)request.getSession().getAttribute(WsConstant.WEBSOCKET_SESSION_KEY);
        if(chatRoom.getUserId()==null){
            chatRoom.setUserId(ssoUser.getUserId());
        }
        roomService.saveOrUpdate(chatRoom);
        return "redirect:/room/roomList.htm";
    }

    @RequestMapping("/roomDelete.htm")
    public String deleteRoom(@RequestParam(value = "roomId")Integer roomId){
        roomService.deleteRoom(roomId);
        return "redirect:/room/roomList.htm";
    }

}
